﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraBars.Docking2010.Views.WindowsUI;
using EduFormManager.Models;
using EduFormManager.Models.Repo;
using EduFormManager.Properties;
using EduFormManager.Utilities;

namespace EduFormManager.Forms.UserControls
{
    public partial class XtraDictionaryCheckControl : XtraBaseControl, ISupportDocumentActions
    {
        private string filepath;
        public XtraDictionaryCheckControl(WindowsUIView view)
            : base(view)
        {
            InitializeComponent();

            EncodingInfo[] eiArray = Encoding.GetEncodings();
            this.comboBoxEncodings.DataSource = eiArray;
            this.comboBoxEncodings.DisplayMember = "Name";
            this.comboBoxEncodings.SelectedItem = eiArray.Single(x => x.Name == "utf-8");
        }

        private void simpleButtonFindCheckFile_Click(object sender, EventArgs e)
        {
            New();
        }

        private void listBoxAllforms_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.textBoxCheckFilename.Text = string.Empty;
            this.richTextBoxCheckFileContent.Text = string.Empty;

            if (allformBindingSource.Current == null)
            {
                return;
            }
            try
            {
                Allform form = (Allform)allformBindingSource.Current;
                byte[] checkData = form.CheckContents;
                if (checkData != null)
                {
                    string crc = FileUtility.GetCRC32AsHexString(checkData);
                    if (crc.Equals(form.CheckfileMD5))
                    {
                        Encoding encoding = Encoding.UTF8; //Encoding.GetEncoding(checkData.CodePage);
                        string textContent = encoding.GetString(checkData == null ? new byte[0] : checkData);
                        this.richTextBoxCheckFileContent.Text = textContent;
                    }
                    else
                    {
                        this.ShowFlyoutMessageBox("Ошибка", "Ошибка целостности данных в БД", FlyoutCommand.OK);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        public void New()
        {
            New(null);
        }

        protected override void New(Document doc)
        {
            using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                DialogResult dialogResult = openFileDialog.ShowDialog(this);
                if (dialogResult == DialogResult.OK)
                {
                    try
                    {
                        filepath = openFileDialog.FileName;
                        String filename = Path.GetFileName(filepath);
                        textBoxCheckFilename.Text = filename;

                        EncodingInfo ei = (EncodingInfo)comboBoxEncodings.SelectedItem;
                        richTextBoxCheckFileContent.Text = File.ReadAllText(filepath, ei.GetEncoding());
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
            }
        }

        public bool CanNew()
        {
            return CanNew(null);
        }

        protected override bool CanNew(Document doc)
        {
            return true;
        }

        public void Save()
        {
            Save(null);
        }

        async protected override void Save(Document doc)
        {
            if (!CanSave())
            {
                this.ShowFlyoutMessageBox("Ошибка", "Не заполнены все поля", FlyoutCommand.OK);
                return;
            }
            Allform form = (Allform)this.allformBindingSource.Current;

            Encoding encoding = (this.comboBoxEncodings.SelectedItem as EncodingInfo).GetEncoding();
            byte[] fileContents = encoding.GetBytes(richTextBoxCheckFileContent.Text);
            string crc = FileUtility.GetCRC32AsHexString(fileContents);

            form.CheckContents = fileContents;

            form.CheckfileMD5 = crc;

            ProgressDialog.ShowTop(this.ParentForm, description: "Сохраняю");

            await RepoHelper.Repo.SaveAsync(form);
            IList<Allform> formList = await RepoHelper.Repo.GetAllAsync<Allform>();
            GuiUtility.UpdateDataBindingSources(this.allformBindingSource, formList);

            ProgressDialog.HideTop();

            this.allformBindingSource.EndEdit();
        }

        public bool CanSave()
        {
            return CanSave(null);
        }

        protected override bool CanSave(Document doc)
        {
            return this.allformBindingSource.Current != null && 
                !String.IsNullOrEmpty(richTextBoxCheckFileContent.Text);
        }

        public void OnQueryDocumentActions(IDocumentActionsArgs args)
        {
            args.DocumentActions.Add(new DocumentAction(CanNew, New) { Caption = "Открыть файл", Image = Resources.glyphicons_144_folder_open });
            args.DocumentActions.Add(new DocumentAction(Save) { Caption = "Сохранить", Image = Resources.glyphicons_206_ok_2 });
        }

        private void comboBoxEncodings_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                EncodingInfo ei = (EncodingInfo)comboBoxEncodings.SelectedItem;
                Encoding encoding = ei.GetEncoding();
                if (!String.IsNullOrEmpty(this.textBoxCheckFilename.Text))
                {
                    richTextBoxCheckFileContent.Text = File.ReadAllText(filepath, encoding);
                }
                else
                {
                    Allform form = allformBindingSource.Current as Allform;
                    if (form != null)
                    {
                        //Encoding sourceEncoding = //Encoding.GetEncoding(form.Checkfile.CodePage);
                        //byte[] converted = Encoding.Convert(sourceEncoding, encoding, form.Checkfile.Contents);
                        //richTextBoxCheckFileContent.Text = encoding.GetString(converted);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
